package cn.hackcloud.demo.dubbo;

import cn.hackcloud.demo.dubbo.dto.SentinelRule;
import cn.hackcloud.demo.dubbo.service.SentinelRuleService;
import com.alibaba.fastjson.JSON;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;

import java.util.ArrayList;
import java.util.List;

/**
 * Zookeeper config sender for demo
 *
 * @author guonanjun
 */
public class ZookeeperConfigSender {

    private static final int RETRY_TIMES = 3;
    private static final int SLEEP_TIME = 1000;

    public static void main(String[] args) throws Exception {
        List<SentinelRule> sentinelRuleList = new ArrayList<>();
        SentinelRule sentinelRule = new SentinelRule("sentinel", 2, 10, 1, "default", 0);
        sentinelRuleList.add(sentinelRule);
        final String rule = JSON.toJSONString(sentinelRuleList);

        CuratorFramework zkClient = CuratorFrameworkFactory.newClient(SentinelRuleService.ZOOKEEPER_ADDRESS, new ExponentialBackoffRetry(SLEEP_TIME, RETRY_TIMES));
        zkClient.start();
        String path = SentinelRuleService.ZOOKEEPER_PATH;
        Stat stat = zkClient.checkExists().forPath(path);
        if (stat == null) {
            zkClient.create().creatingParentContainersIfNeeded().withMode(CreateMode.PERSISTENT).forPath(path, null);
        }
        zkClient.setData().forPath(path, rule.getBytes());

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        zkClient.close();
    }

    private static String getPath(String groupId, String dataId) {
        String path = "";
        if (groupId.startsWith("/")) {
            path += groupId;
        } else {
            path += "/" + groupId;
        }
        if (dataId.startsWith("/")) {
            path += dataId;
        } else {
            path += "/" + dataId;
        }
        return path;
    }
}
